// eslint-disable-next-line import/no-extraneous-dependencies, max-classes-per-file
const { Service } = require('egg')
const cheerio = require('cheerio')
const fs = require('fs')

// 定义两个类，用来存储专业和班级
class Major {
  constructor(name, departmentId) {
    this.label = name
    this.value = departmentId
    this.children = [] // 存储班级
  }

  // 内置方法，用来添加班级
  addClass(classData) {
    this.children.push(classData)
  }
}

class Class {
  constructor(data) {
    this.label = data.bj
    this.value = data.bh_id // 班级名称
  }
}

module.exports = class TreeService extends Service {
  /**
   * * 班级  学期 —— 学院 —— 年级 —— 专业 —— 班级
   * @return {Object} *
   */
  async class_() {
    const Cookie = this.ctx.state.Cookie
    const { term } = this.ctx.data
    // eslint-disable-next-line no-unused-vars, prefer-const, @typescript-eslint/no-unused-vars
    let [xnm, _, xqm] = term ? term.split('-') : ['', '', '']
    if (term) { xqm = xqm === '1' ? '3' : (xqm === '2' ? '12' : (xqm === '3' ? '16' : '')) }
    console.log('xqm', xqm)
    const tree = {
      [term]: [],
    }
    console.log('!xqm', !xqm)
    if (!(xqm === '')) {
    /* 最初的网页 */
      const firstUrl = `${this.ctx.state.baseUrl}/jwglxt/kbdy/bjkbdy_cxBjkbdyIndex.html?_t=1711849563055&gnmkdm=N214505`
      const firRes = await this.ctx.curl(firstUrl, { headers: { Cookie } })
      /* 没有学院号的网页 */
      const apiUrl = `${this.ctx.state.baseUrl}/jwglxt/kbdy/bjkbdy_cxBjkbdyTjkbList.html?gnmkdm=N214505`/* gnmkdm=N214505好像会变化 */
      const res = await this.ctx.curl(apiUrl, {
        method: 'POST',
        data: {
          xnm,
          xqm,
          xqh_id: '',
          njdm_id: '',
          jg_id: '',
          zyh_id: '',
          zyfx_id: '',
          bh_id: '',
          xsdm: '',
          pyccdm: '',
          kclxdm: '',
          _search: false,
          nd: '1711847862719',
          'queryModel.showCount': '5000',
          'queryModel.currentPage': '1',
          'queryModel.sortName': '',
          'queryModel.sortOrder': 'asc',
          time: '1',
        },
        headers: {
          Cookie,
          'Content-Type': 'application/x-www-form-urlencoded',
          'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
        },
        timeout: 10000,
      })

      if (firRes.status === 200 && res.status === 200) {
        const data = JSON.parse(res.data.toString())// 获取除学院外其他的数据
        try
        { const $ = cheerio.load(firRes.data.toString())
          const jg = $('#jg_id').find('option')
          const xyList = []// 学院表格
          jg.each((e) => (xyList.push({
            label: jg[e].children[0].data,
            value: jg[e].attribs.value,
            children: [],
          })))
          xyList.sort((a, b) => a.label.length - b.label.length)// 对学院按照名字长度升序
          tree[term] = xyList.slice(1, xyList.length)// 去除'全部'这个选项
          data.items.forEach((item) => { // 遍历所有的数据
            tree[term].forEach((xy) => { // 遍历树里面的学院信息
              if (xy.label === item.jgmc) { // 存入年级信息
                xy.children.push({
                  label: item.njmc,
                  value: item.njdm_id,
                  children: [],
                })
              }
              // 删除重复的年级信息-为什么要这样删除，因为，遍历所有数据获取的年级，而非自行构造的。
              // obj-当前遍历的元素；index-当前遍历的索引；self-当前数组
              // 找到当前元素的索引，如果与当前索引相同，说明当前元素是唯一的，需要插入
              const uniqueList = xy.children.filter((obj, index, self) => self.findIndex((o) => o.label === obj.label
              && o.value === obj.value) === index)
              uniqueList.sort((a, b) => a.label - b.label)
              xy.children = uniqueList
            })
          })
          data.items.forEach((record) => {
          // 已经保证所有学院都在
            const departmentXy = tree[term].find((xy) => xy.label === record.jgmc)
            if (departmentXy) {
              const departmentNj = departmentXy.children.find((nj) => nj.label === record.njmc)
              if (departmentNj) {
                if (!departmentNj.children.find((zy) => zy.label === record.zymc)) {
                  departmentNj.children.push(new Major(record.zymc, record.zyh_id))
                }
                const departmentBj = departmentNj.children.find((zy) => zy.label === record.zymc)
                if (!departmentBj.children.find((bj) => bj.label === record.bj)) {
                  departmentBj.addClass(new Class(record))
                }
              }
            }
          })
          /* 储存 */
          const filePath = './app/public/tree-class.json'
          // 判断文件是否存在
          // 文件存在，读取文件内容
          fs.promises.access(filePath, fs.constants.F_OK).then(() => fs.promises.readFile(filePath, 'utf-8'))
            .then((data1) => {
              // 文件内容转为对象
              const jsonData = JSON.parse(data1)
              jsonData[term] = tree[term]
              fs.writeFileSync(filePath, JSON.stringify(jsonData))
            })
            .catch((err) => {
              if (err.code === 'ENOENT') {
                fs.writeFileSync(filePath, JSON.stringify(tree))
              } else {
                console.error('读取文件出错', err)
              }
            })
          return tree
        } catch (err) {
          console.log('err', err)
          throw err
        }
      }
    }
    return tree
  }
}
